import { createSlice } from '@reduxjs/toolkit'
import {getToken,setToken,clearToken} from '@/utils'
import {LonginApi,GetuserInfoApi} from '@/apis/user'

const userStore = createSlice({
  name: 'user',
  // 数据状态
  initialState: {
    token:getToken() || '',
    userInfo:{}
  },
  // 同步修改方法
  reducers: {
    setUserToken (state, action) {
      state.token = action.payload
      setToken(action.payload)
    },
    setUserInfo(state, action) {
      state.userInfo = action.payload
    },
    clearUserInfo(state) {
      state.token = ''
      state.userInfo={}
      clearToken()
    }
  }
})

// 解构出actionCreater
const { setUserToken,setUserInfo,clearUserInfo } = userStore.actions

// 获取reducer函数
const userReducer = userStore.reducer

// 异步方法封装
const fetchLogin = (loginForm) => {
  return async (dispatch) => {
    try {
      const res = await LonginApi(loginForm)
      dispatch(setUserToken(res.data.token))
    } catch (error) {
      console.log("error:",error)
    }
  }
}

const fetchUserInfo = () => {
  return async (dispatch) => {
    try {
      const res = await GetuserInfoApi()
      dispatch(setUserInfo(res.data))
    } catch (error) {
      console.log("error:",error)
    }
  }
}

export { fetchLogin,fetchUserInfo,clearUserInfo }

export default userReducer